from tables import openFile, Float32Atom
    


class H5FILE():
    
    def open(self):
        pass
    
    def close(self, GPR):
        self.h5file.close()
        
    def display(self):
        print self.h5file
    
    def new(self, filename=None, dims=(1024, 0)):
        self.h5file = openFile(filename+'.h5', mode = 'w', title = 'GPR data file')
        self.group_data = self.h5file.createGroup(self.h5file.root, 'data', 'GPR data')
        self.earray_data = self.h5file.createEArray(self.group_data, 'traces', Float32Atom(), dims,
                                                 expectedrows=5000)
        
    def append_earray_data(self, data):
        self.earray_data.append(data)
        self.h5file.flush()

    def set_metadata(self, GPR):
        self.earray_data.attrs.deltaT = GPR.deltaT
        try:
            self.earray_data.attrs.gatefreq = GPR.gatefreq
        except AttributeError:
            pass
        self.earray_data.attrs.cmed = GPR.cmed 
        self.earray_data.attrs.nstacks = GPR.nstacks
        self.earray_data.attrs.hascoords = GPR.hascoords
        self.earray_data.attrs.filename = GPR.filename
        self.earray_data.attrs.proclog = GPR.proclog
        
    def save(self, GPR):
        pass
        
        
class COORDS():
    
    def __init__(self):
        pass
    
    
class Picks():
    
    def __init__(self):
        self.trace = []
        self.twt = []
        self.x = []
        self.y = []
        self.elev = []
        self.tell = 0 # counts the picks
        self.pltid = 0 # controls if picks are plotted
         
    def append(self, trace, twt, x, y, elev):
        self.trace.append(trace)
        self.twt.append(twt)
        self.x.append(x)
        self.y.append(y)
        self.elev.append(elev)  
        self.tell += 1      

    def save(self, file):
        fid = open(file, 'w')
        fid.write("#trace, twt, x, y, elev\n")
        for n in range(self.tell):
            fid.write('%i, %f, %f, %f, %f\n' % (self.trace[n], self.twt[n], self.x[n], self.y[n], self.elev[n]))
        fid.close()    
        
    def load(self, file):
        fid = open(file, 'r')
        data = fid.readlines()
        fid.close()
        self.tell = len(data)
        for n in range(self.tell):
            self.trace[n], self.twt[n], self.x[n], self.y[n] = data[n].split(' ')